//
//  JLSHeadlineViewController.m
//  看点
//
//  Created by 焦林生 on 15/12/16.
//  Copyright © 2015年 jiaolinsheng. All rights reserved.
//

#import "JLSHeadlineViewController.h"
#import "JLSHeadline.h"
#import "JLSHeadlineCell.h"
#import "JLSHTTPManager.h"
#import "JLSNewsDetailViewController.h"


@interface JLSHeadlineViewController ()
/**
 *  存放模型的数组
 */
@property (nonatomic, strong) NSArray *headlines;
@end

@implementation JLSHeadlineViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //发送请求,加载数据
    [self setupRequest];
    
}
#pragma mark - 发送请求,加载数据
- (void)setupRequest
{

    //根据域名拼接 URL 请求路径
    NSString *domainUrl = [kNetEaseDomain stringByAppendingString:self.urlString];
    domainUrl = [NSString stringWithFormat:@"%@/0-140.html",domainUrl];
    
    //向服务器发送请求
    [[JLSHTTPManager manager] GET:domainUrl parameters:nil success:^(AFHTTPRequestOperation *  operation, NSDictionary *   responseObject) {
        
        //成功回调
        NSArray *dictArray = responseObject[self.urlString];
        NSMutableArray *modelArray = [NSMutableArray array];
        for (NSDictionary *dict in dictArray) {
            JLSHeadline *headline = [[JLSHeadline alloc] initWithDict:dict];
            [modelArray addObject:headline];
        }
        self.headlines  = modelArray;
        
        //一定要刷新 tableView,否则没有数据
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
        
        //失败回调
        [MBProgressHUD showError:@"网络繁忙,请稍后再试"];
    }];
}

#pragma mark - 数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.headlines.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    //1 获取模型
    JLSHeadline *headline = self.headlines[indexPath.row];
    
    //2 使用 cell 模板来创建 cell
    NSString *ID = [JLSHeadlineCell headlineCellWithIdentifier:headline];
    JLSHeadlineCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    //设置 cell
    cell.headline = headline;
    
    //返回 cell
    return cell;
}

#pragma mark - 代理方法
//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    JLSHeadline *headline = self.headlines[indexPath.row];
    if (headline.imgextra.count == 2) {
        return 120;
    }
    if (headline.isBigImaga) {
        return 180;
    }
    return 80;
}

#pragma mark - 在控制器跳转之前的准备工作
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

    //1 获取 tableView 选中的行
    NSUInteger row = self.tableView.indexPathForSelectedRow.row;
    //2 创建目标控制器
    JLSNewsDetailViewController *news = segue.destinationViewController;
    //3 给目标控制器传递数据
    news.headline = self.headlines[row];
}





@end
